package weixin

import (
	"bytes"
	"encoding/json"
	"fmt"
	"hft/global"
	"hft/tools"
	"hft/tools/weixin/model"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// 微信公众号api封装

type WeiXin struct{}

// 基础请求
func (w *WeiXin) baseRequest(path string, method string, params *url.Values, newD []byte) (data []byte, err error) {
	fmt.Println(path)
	request, err := url.Parse(global.OC_CONFIG.WeiXin.BaseUrl + path + "&" + params.Encode())
	if err != nil {
		return nil, err
	}

	var resp *http.Request

	if method == "POST" {

		resp, err = http.NewRequest(method, request.String(), bytes.NewBuffer(newD))

		resp.Header.Set("Content-Type", "application/json; charset=UTF-8")

	} else if method == "GET" {
		resp, err = http.NewRequest(method, request.String(), strings.NewReader(params.Encode()))
	}

	if err != nil {
		return nil, err
	}

	fmt.Println(resp.Header.Get("Content-Type"))

	client := &http.Client{}

	result, err := client.Do(resp)

	if err != nil {
		return nil, err
	}

	defer result.Body.Close()

	resBody, err := ioutil.ReadAll(result.Body)

	if err != nil {
		return nil, err
	}

	return resBody, nil
}

func (w *WeiXin) GetToken() (res string) {

	var params = &url.Values{
		"grant_type": []string{"client_credential"},
		"appid":      []string{global.OC_CONFIG.WeiXin.AppId},
		"secret":     []string{global.OC_CONFIG.WeiXin.AppSecret},
	}
	data, _ := w.baseRequest("/cgi-bin/token?"+params.Encode(), "GET", &url.Values{}, []byte(""))

	var tokenRes *model.TokenRes

	fmt.Println("返回", string(data))

	json.Unmarshal(data, &tokenRes)

	// 设置token

	global.OC_REDIS.Set(tools.Md5("weixin_token"), tokenRes.AccessToken, time.Duration(tokenRes.ExpiresIn*int(time.Second)))

	return tokenRes.AccessToken
}

func (w *WeiXin) BaseRequestV2(method string, path string, params *url.Values, newD []byte) (data []byte) {

	// 先获取当前的token 看看是否过去

	var nowToken string
	oldToken, err := global.OC_REDIS.Get(tools.Md5("weixin_token")).Result()
	if err != nil || oldToken == "" {
		fmt.Println("sss")
		nowToken = w.GetToken()
	} else {
		nowToken = oldToken
	}

	res, _ := w.baseRequest(path+"?access_token="+nowToken, method, params, newD)

	return res

}

var WeiXinBase = new(WeiXin)
